package com.yanqu.road.dataHelper.action.excel;

import com.yanqu.road.dataHelper.action.zhounianqing.BanquetCount;
import com.yanqu.road.dataHelper.action.zhounianqing.MammonCount;
import com.yanqu.road.dataHelper.gameServer.GameServer;
import com.yanqu.road.dataHelper.manager.ServerMgr;
import com.yanqu.road.dataHelper.repair.BaseRepair;
import com.yanqu.road.entity.marriage.MarriageInfo;
import com.yanqu.road.entity.player.*;
import com.yanqu.road.utils.string.StringUtils;

import java.math.BigInteger;
import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.MessageFormat;
import java.util.*;

/**
 * @Author yyq、wmm
 * @Date 2021/07/12
 */
public class ZhouNianRankLogic extends BaseRepair {

    public ZhouNianRankLogic(GameServer gameServer) {
        super(gameServer);
    }

    @Override
    public void repair(long param1, String param2) {

    }

    public List<ZhouNianQingRankData> getServerRankList(long serverId, List<Integer> typeList, int size, int rankType) {
        PreparedStatement call = null;
        String sql = "select * from " +
                "(select activityId,userId,max(value+0) as value0 from t_u_activity_condition where type in ("+ StringUtils.listToString(typeList, ",") +") GROUP BY userId)t " +
                "ORDER BY t.value0 desc limit ?;";
        List<ZhouNianQingRankData> zhouNianQingRankDataList = new ArrayList<>();
        try {
            call = getGameServer().getConnection().prepareStatement(sql);
            int i = 1;
            call.setInt(i++, size);
            ResultSet rs = call.executeQuery();
            while (rs.next()) {
                int activityId = rs.getInt("activityId");
                long userId = rs.getLong("userId");
                String value = rs.getString("value0");
                zhouNianQingRankDataList.add(new ZhouNianQingRankData(activityId, serverId, userId, rankType, value));
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            getGameServer().closeConnection(call, null);
        }
        return zhouNianQingRankDataList;
    }

    public List<ZhouNianQingRankData> getServerRankListByActivityId(long serverId, List<Integer> activityIdList, int size, int rankType) {
        PreparedStatement call = null;

        String sql = "select activityId,userId,value+0 as value0 from t_u_activity_condition where activityId in ("+ StringUtils.listToString(activityIdList, ",")+") ORDER BY value0 desc";
        List<ZhouNianQingRankData> zhouNianQingRankDataList = new ArrayList<>();
        try {
            call = getGameServer().getConnection().prepareStatement(sql);
            int i = 1;
            ResultSet rs = call.executeQuery();
            Set<Long> userSet = new HashSet<>();

            while (rs.next()) {
                int activityId = rs.getInt("activityId");
                long userId = rs.getLong("userId");
                String value = rs.getString("value0");
                if (userSet.contains(userId)) {
                    continue;
                }
                if (new BigInteger(value).compareTo(BigInteger.ONE) < 0) {
                    continue;
                }
                userSet.add(userId);
                zhouNianQingRankDataList.add(new ZhouNianQingRankData(activityId, serverId, userId, rankType, value));
                if (zhouNianQingRankDataList.size() >= size) {
                    break;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            getGameServer().closeConnection(call, null);
        }
        return zhouNianQingRankDataList;
    }


    public Map<Long,List<Integer>> getUserBeauty() {
        Map<Long,List<Integer>> dataMap = new HashMap<>();
        ResultSet rs = null;
        CallableStatement call = null;
        String sql = "select userId,beautyId from t_u_beauty  ";
        try {
            call = getGameServer().getConnection().prepareCall(sql);
            int i = 1;
            rs = call.executeQuery();
            while (rs.next()) {
                long userId = rs.getLong("userId");
                int beautyId = rs.getInt("beautyId");
                if (!dataMap.containsKey(userId)) {
                    dataMap.put(userId, new ArrayList<>());
                }
                dataMap.get(userId).add(beautyId);
            }
        } catch (SQLException ex) {
            getGameServer().getLogger().error("异常错误", ex);
        } finally {
            getGameServer().closeConnection(call, rs);
        }
        return dataMap;
    }

    public Map<Long,List<Integer>> getUserSkin() {
        Map<Long,List<Integer>> dataMap = new HashMap<>();
        ResultSet rs = null;
        CallableStatement call = null;
        String sql = "select userId,skinId from t_u_skin ";
        try {
            call = getGameServer().getConnection().prepareCall(sql);
            int i = 1;
            rs = call.executeQuery();
            while (rs.next()) {
                long userId = rs.getLong("userId");
                int beautyId = rs.getInt("skinId");
                if (!dataMap.containsKey(userId)) {
                    dataMap.put(userId, new ArrayList<>());
                }
                dataMap.get(userId).add(beautyId);
            }
        } catch (SQLException ex) {
            getGameServer().getLogger().error("异常错误", ex);
        } finally {
            getGameServer().closeConnection(call, rs);
        }
        return dataMap;
    }

    //所有美女
    public List<UserBeauty> getUserBeauty(long userId) {
        List<UserBeauty> result = new ArrayList<>();
        ResultSet rs = null;
        CallableStatement call = null;
        String sql = "select userId,beautyId,intimacy,skinIntimacy,skinId,quality from t_u_beauty where userId = ?";
        try {
            call = getGameServer().getConnection().prepareCall(sql);
            int i = 1;
            call.setLong(i, userId);
            rs = call.executeQuery();
            while (rs.next()) {
                UserBeauty ub = new UserBeauty();
                long uid = rs.getLong("userId");
                int beautyId = rs.getInt("beautyId");
                int skinIntimacy = rs.getInt("skinIntimacy");
                int intimacy = rs.getInt("intimacy");
                ub.setUserId(uid);
                ub.setIntimacy(intimacy);
                ub.setSkinIntimacy(skinIntimacy);
                ub.setBeautyId(beautyId);
                ub.setSkinId(rs.getInt("skinId"));
                ub.setQuality(rs.getInt("quality"));
                result.add(ub);
            }
        } catch (SQLException ex) {
            getGameServer().getLogger().error("异常错误", ex);
        } finally {
            getGameServer().closeConnection(call, rs);
        }
        return result;
    }

    //所有子嗣(取成婚数据)
    public List<MarriageInfo> getUserAllChild(long userId, long beginSecond, long endSecond) {
        List<MarriageInfo> result = new ArrayList<>();
        ResultSet rs = null;
        CallableStatement call = null;
        String sql = "select childTalent,childSex,childOccupation,childName,childHeadIcon,childEarnSpeed,isTwins from t_u_marriage where userId = ? and childAdultTime >= ? and childAdultTime < ?";
        try {
            call = getGameServer().getConnection().prepareCall(sql);
            int i = 1;
            call.setLong(i++, userId);
            call.setLong(i++, beginSecond);
            call.setLong(i++, endSecond);
            rs = call.executeQuery();
            while (rs.next()) {
                MarriageInfo data = new MarriageInfo();
                data.setChildTalent(rs.getInt("childTalent"));
                data.setChildSex(rs.getInt("childSex"));
                data.setChildOccupation(rs.getInt("childOccupation"));
                data.setChildName(rs.getString("childName"));
                data.setChildHeadIcon(rs.getInt("childHeadIcon"));
                data.setChildEarnSpeed(new BigInteger(rs.getString("childEarnSpeed")));
                data.setTwins(rs.getBoolean("isTwins"));
                result.add(data);
            }
        } catch (SQLException ex) {
            getGameServer().getLogger().error("异常错误", ex);
        } finally {
            getGameServer().closeConnection(call, rs);
        }
        return result;
    }

    //联姻总子嗣赚速（仅亲家)
    public BigInteger getPartnerChildEarnSpeed(long userId, long beginSecond, long endSecond) {
        ResultSet rs = null;
        CallableStatement call = null;
        String sql = "select SUM(partnerChildEarnSpeed) as totalEarnSpeed from t_u_marriage_record where userId = ? and marriageTime >= ? and marriageTime < ?;";
        try {
            call = getGameServer().getConnection().prepareCall(sql);
            int i = 1;
            call.setLong(i++, userId);
            call.setLong(i++, beginSecond);
            call.setLong(i++, endSecond);
            rs = call.executeQuery();
            if (rs.next()) {
                String totalEarnSpeed = rs.getString("totalEarnSpeed");
                if(StringUtils.isNullOrEmpty(totalEarnSpeed)){
                    return BigInteger.ZERO;
                }
                return new BigInteger(totalEarnSpeed);
            }
        } catch (SQLException ex) {
            getGameServer().getLogger().error("异常错误", ex);
        } finally {
            getGameServer().closeConnection(call, rs);
        }
        return BigInteger.ZERO;
    }

    //最强子嗣
    public UserPowerChild getUserPowerChild(long userId) {
        ResultSet rs = null;
        CallableStatement call = null;
        String sql = "select childUid,childTalent,childSex,childOccupation,childName,childHeadIcon,childEarnSpeed,isTwins from t_u_power_child where userId = ?";
        try {
            call = getGameServer().getConnection().prepareCall(sql);
            int i = 1;
            call.setLong(i, userId);
            rs = call.executeQuery();
            if (rs.next()) {
                UserPowerChild upc = new UserPowerChild();
                String uid = rs.getString("childUid");
                int childTalent = rs.getInt("childTalent");
                int childSex = rs.getInt("childSex");
                int childOccupation = rs.getInt("childOccupation");
                String childName = rs.getString("childName");
                int childHeadIcon = rs.getInt("childHeadIcon");
                String childEarnSpeed = rs.getString("childEarnSpeed");
                boolean isTwins = rs.getBoolean("isTwins");
                upc.setChildUid(uid);
                upc.setChildTalent(childTalent);
                upc.setChildSex(childSex);
                upc.setChildOccupation(childOccupation);
                upc.setChildName(childName);
                upc.setChildHeadIcon(childHeadIcon);
                if(!StringUtils.isNullOrEmpty(childEarnSpeed)){
                    upc.setChildEarnSpeed(new BigInteger(childEarnSpeed));
                }else {
                    upc.setChildEarnSpeed(BigInteger.ZERO);
                }
                upc.setIsTwins(isTwins);
                return upc;
            }
        } catch (SQLException ex) {
            getGameServer().getLogger().error("异常错误", ex);
        } finally {
            getGameServer().closeConnection(call, rs);
        }
        return null;
    }

    //所有门客
    public List<UserPatrons> getUserPatrons(long userId) {
        List<UserPatrons> result = new ArrayList<>();
        ResultSet rs = null;
        CallableStatement call = null;
        String sql = "select patronsId,skinId,ability from t_u_patrons where userId = ?";
        try {
            call = getGameServer().getConnection().prepareCall(sql);
            int i = 1;
            call.setLong(i, userId);
            rs = call.executeQuery();
            while (rs.next()) {
                UserPatrons data = new UserPatrons();
                data.setPatronsId(rs.getInt("patronsId"));
                data.setSkinId(rs.getInt("skinId"));
                String ability = rs.getString("ability");
                if(!StringUtils.isNullOrEmpty(ability)){
                    data.setAbility(new BigInteger(ability));
                }else {
                    data.setAbility(BigInteger.ZERO);
                }
                result.add(data);
            }
        } catch (SQLException ex) {
            getGameServer().getLogger().error("异常错误", ex);
        } finally {
            getGameServer().closeConnection(call, rs);
        }
        return result;
    }

    public UserInfo getUserInfo(long userId){
        ResultSet rs = null;
        CallableStatement call = null;
        String sql = "select earnSpeed from t_u_user where userId = ?";
        try {
            call = getGameServer().getConnection().prepareCall(sql);
            int i = 1;
            call.setLong(i, userId);
            rs = call.executeQuery();
            if (rs.next()) {
                UserInfo user = new UserInfo();
                String earnSpeed = rs.getString("earnSpeed");
                if(!StringUtils.isNullOrEmpty(earnSpeed)){
                    user.setEarnSpeed(new BigInteger(earnSpeed));
                }else {
                    user.setEarnSpeed(BigInteger.ZERO);
                }
                return user;
            }
        } catch (SQLException ex) {
            getGameServer().getLogger().error("异常错误", ex);
        } finally {
            getGameServer().closeConnection(call, rs);
        }
        return null;
    }

    public UserAttribute getUserAttribute(long userId, int attrId){
        ResultSet rs = null;
        CallableStatement call = null;
        int tableIndex = (int) (userId % 16);
        String sql = MessageFormat.format("select * from t_u_attr_{0} where userId =? and attrId=?", tableIndex);
        try {
            call = getGameServer().getConnection().prepareCall(sql);
            int i = 1;
            call.setLong(i++, userId);
            call.setInt(i++, attrId);
            rs = call.executeQuery();
            if (rs.next()) {
                UserAttribute attribute = new UserAttribute();
                long value = rs.getLong("value");
                attribute.setValue(value);
                return attribute;
            }
        } catch (SQLException ex) {
            getGameServer().getLogger().error("异常错误", ex);
        } finally {
            getGameServer().closeConnection(call, rs);
        }
        return null;
    }

    //称号统计
    public List<MammonCount> getMammonCount(List<Integer> decorationList, String endTimeStr){
        List<MammonCount> result = new ArrayList<>();
        ResultSet rs = null;
        CallableStatement call = null;
        String sql = "select userId,decorationId,count(decorationId) as count0 " +
        " from t_l_decoration " +
        " where decorationId in("+ StringUtils.listToString(decorationList, ",")+ ") "+
                "and time < ? GROUP BY decorationId,userId order by userId";
        try {
            call = getGameServer().getLogConnection().prepareCall(sql);
            call.setString(1, endTimeStr);
            rs = call.executeQuery();
            while (rs.next()) {
                long uid = rs.getLong("userId");
                int decorationId = rs.getInt("decorationId");
                int count = rs.getInt("count0");
                MammonCount mammonCount = new MammonCount(uid, decorationId, count);
                result.add(mammonCount);
            }
        } catch (SQLException ex) {
            getGameServer().getLogger().error("异常错误", ex);
        } finally {
            getGameServer().closeConnection(call, rs);
        }
        return result;
    }


    //统计玩家-本服宴会人气/场次
    public Map<Long, List<BanquetCount>> getServerBanquet(long userId, long beginTime, long endTime){
        Map<Long, List<BanquetCount>> dataMap = new HashMap<>();
        ResultSet rs = null;
        CallableStatement call = null;
        String sql = "select userId,type,sum(popularity) as total,count(type) as count0 " +
                " from t_u_banquet where userId = ? and openTime >= ? and openTime < ? " +
                " group by type ";
        try {
            int i = 1;
            call =  getGameServer().getConnection().prepareCall(sql);
            call.setLong(i++, userId);
            call.setLong(i++, beginTime);
            call.setLong(i++, endTime);
            rs = call.executeQuery();
            while (rs.next()) {
                long uid = rs.getLong("userId");
                int type = rs.getInt("type");
                int count = rs.getInt("count0");
                int total = rs.getInt("total");
                BanquetCount banquetCount = new BanquetCount(uid, type, count, total);
                if(!dataMap.containsKey(uid)){
                    dataMap.put(uid, new ArrayList<>());
                }
                dataMap.get(uid).add(banquetCount);
            }
        } catch (SQLException ex) {
            getGameServer().getLogger().error("异常错误", ex);
        } finally {
            getGameServer().closeConnection(call, rs);
        }
        return dataMap;
    }

    //统计玩家-跨服宴会人气/场次
    public Map<Long, List<BanquetCount>> getCrossServerBanquet(long userId, long beginTime, long endTime){
        Map<Long, List<BanquetCount>> dataMap = new HashMap<>();
        ResultSet rs = null;
        CallableStatement call = null;
        String sql = "select userId,type,sum(popularity) as total,count(type) as count0 " +
                " from t_u_banquet_cross where userId = ? and openTime >= ? and openTime < ? " +
                " group by type ";
        try {
            int i = 1;
            call =  getGameServer().getConnection().prepareCall(sql);
            call.setLong(i++, userId);
            call.setLong(i++, beginTime);
            call.setLong(i++, endTime);
            rs = call.executeQuery();
            while (rs.next()) {
                long uid = rs.getLong("userId");
                int type = rs.getInt("type");
                int count = rs.getInt("count0");
                int total = rs.getInt("total");
                BanquetCount banquetCount = new BanquetCount(uid, type, count, total);
                if(!dataMap.containsKey(uid)){
                    dataMap.put(uid, new ArrayList<>());
                }
                dataMap.get(uid).add(banquetCount);
            }
        } catch (SQLException ex) {
            getGameServer().getLogger().error("异常错误", ex);
        } finally {
            getGameServer().closeConnection(call, rs);
        }
        return dataMap;
    }


    public void fillActivityInfo(List<ZhouNianQingRankData> serverRankList) {
        List<Integer> activityList = new ArrayList<>();
        for (ZhouNianQingRankData rankData : serverRankList) {
            if(!activityList.contains(rankData.getActivityId())){
                activityList.add(rankData.getActivityId());
            }
        }
        //填充活动数据
        Map<Integer, Long> endTimeMap = new ServerMgr().getActivityEndTime(activityList);
        for (ZhouNianQingRankData rankData : serverRankList) {
            rankData.setDataTime(endTimeMap.get(rankData.getActivityId()));
        }
    }
}
